<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col
              :md="5"
              :sm="10">
              <a-form-item label="项目名称">
                <a-input
                  v-model="queryParam.projectName"
                  placeholder="" />
              </a-form-item>
            </a-col>
            <a-col
              :md="5"
              :sm="10">
              <a-form-item label="项目类型">
                <a-select
                  v-model="queryParam.projectTypeId"
                  placeholder="请选择"
                  default-value="0">
                  <a-select-option
                    v-for="i in projectTypes"
                    :key="i.projectTypeId"
                    :value="i.projectTypeId">
                    {{ i.projectType }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="5"
              :sm="10">
              <a-form-item label="负责人">
                <a-select
                  show-search
                  :filter-option="filterOption"
                  v-model="queryParam.managerName"
                  placeholder="请选择负责人">
                  <a-select-option
                    v-for="i in staffs"
                    :key="i.userId"
                    :value="i.name">
                    {{ i.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="5"
              :sm="10">
              <a-form-item label="客户">
                <a-select
                  show-search
                  :filter-option="filterOption"
                  v-model="queryParam.customerName"
                  placeholder="请选择客户">
                  <a-select-option
                    v-for="i in customers"
                    :key="i.customerId"
                    :value="i.companyName">
                    {{ i.companyName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="4"
              :sm="10">
              <span
                class="table-page-search-submitButtons"
                :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button
                  type="primary"
                  v-if="list"
                  @click="$refs.table.refresh(true)">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  v-if="list"
                  @click="() => this.queryParam = {}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button
          type="primary"
          icon="plus"
          v-if="save"
          @click="handleAdd">新建</a-button>
      </div>
      <div>
        <s-table
          ref="table"
          size="default"
          rowKey="projectId"
          :columns="columns"
          :data="loadData"
          :customRow="tableCustomRow"
          showPagination="auto">
          <span
            slot="serial"
            slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span
            slot="status"
            slot-scope="text">
            <a-badge
              :status="text | statusTypeFilter"
              :text="text | statusFilter" />
          </span>
          <span
            slot="createTime"
            slot-scope="text, record">
            {{ record.createTime.split(' ')[0] }}
          </span>
          <span
            slot="completeTime"
            slot-scope="text, record">
            {{ record.completeTime.split(' ')[0] }}
          </span>
          <span
            slot="description"
            slot-scope="text">
            <ellipsis
              :length="10"
              tooltip>{{ text }}</ellipsis>
          </span>
          <span
            slot="action"
            slot-scope="text, record">
            <template>
              <a v-if="update" @click="handleEdit(record)">配置</a>
              <a-divider type="vertical" />
              <a v-if="detail" @click="handleInfo(record)">详情</a>
            </template>
          </span>
        </s-table>
      </div>
      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :isAdd="isAdd"
        :projectTypes="projectTypes"
        @resetProjectTypes="resetProjectTypes"
        :customers="customers"
        :staffs="staffs"
        @cancel="handleCancel"
        @ok="handleOk" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { getProjectList, saveProject, updateProject, getAllProjectType, getAllCustom, allStaff } from '@/api/manage'
import CreateForm from './modules/CreateForm'
import { isInMenu } from '../config.js'
import { mapGetters } from 'vuex'

const columns = [
  {
    title: '#',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    scopedSlots: { customRender: 'createTime' }
  },
  {
    title: '项目名称',
    dataIndex: 'projectName'
  },
  {
    title: '业务员',
    dataIndex: 'salesName'
  },
  {
    title: '项目类型',
    dataIndex: 'projectTypeName'
  },
  {
    title: '计划交付时间',
    dataIndex: 'completeTime',
    scopedSlots: { customRender: 'completeTime' }
  },
  {
    title: '负责人',
    dataIndex: 'managerName'
  },
  {
    title: '客户',
    dataIndex: 'customerName'
  },
  {
    title: '状态',
    dataIndex: 'statusName'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
           // 权限参数
      list: false, // 列表
      save: false, // 家
      deleteBtn: false, // 删
      update: false, // 改
      detail: false, // 详情
      // create model
      visible: false,
      confirmLoading: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = { page: parameter.pageNo, limit: parameter.pageSize }
        const param = Object.assign({}, this.queryParam)
        if (this.queryParam.sendDate) {
          param.sendBeginDate = this.queryParam.sendDate[0]
          param.sendEndDate = this.queryParam.sendDate[1]
        }
        if (this.queryParam.signDate) {
          param.receiveBeginDate = this.queryParam.signDate[0]
          param.receiveEndDate = this.queryParam.signDate[1]
        }
        param.sendDate = undefined
        param.signDate = undefined
        return this.list && getProjectList(Object.assign({}, param, requestParameters, { entryDate: undefined })).then(res => {
          return Object.assign({}, res, {
            totalCount: res.total,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize
          })
        })
      },
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null,
      isAdd: false,
      projectTypes: [],
      staffs: [],
      customers: []
    }
  },
  computed: {
    ...mapGetters(['menu'])
  },
  created () {
    // 点击查看客户
    this.list = isInMenu(this.menu, 'ROLE_but:project:list')
    // 增加
    this.save = isInMenu(this.menu, 'ROLE_but:project:save') && isInMenu(this.menu, 'ROLE_but:projectType:select') && isInMenu(this.menu, 'ROLE_but:customer:select') && isInMenu(this.menu, 'ROLE_but:user:select')
    // 改
    this.update = isInMenu(this.menu, 'ROLE_but:project:update') && isInMenu(this.menu, 'ROLE_but:projectType:select') && isInMenu(this.menu, 'ROLE_but:customer:select') && isInMenu(this.menu, 'ROLE_but:user:select')
    this.detail = isInMenu(this.menu, 'ROLE_page:projectInfo')
},
  mounted () {
    // 查询所有的项目类型
    getAllProjectType().then(res => {
      if (res.code === 0) {
        this.projectTypes = res.data
      }
    })
    // 查询所有的客户
    getAllCustom().then(res => {
      if (res.code === 0) {
        this.customers = res.data
      }
    })
    // 查询所有的员工allStaff
    allStaff().then(res => {
      if (res.code === 0) {
        this.staffs = res.data
      }
    })
  },
  methods: {
    handleAdd () {
      this.$refs.createModal.form.resetFields()
      this.isAdd = true
      this.visible = true
    },
    handleEdit (record) {
      this.$refs.createModal.form.resetFields()
      const form = this.$refs.createModal.form
      this.isAdd = false
      this.visible = true
      this.$nextTick(() => {
        form.setFieldsValue(record)
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (this.isAdd) {
            saveProject(values).then(res => {
              if (res.code === 0) {
                this.visible = false
                this.$refs.table.refresh()
                this.$message.info('新增成功')
                form.resetFields()
              }
            }).finally(() => { this.confirmLoading = false })
          } else {
            updateProject(Object.assign({}, values)).then(res => {
              if (res.code === 0) {
                this.visible = false
                this.$refs.table.refresh()
                this.$message.info('配置成功')
                form.resetFields()
              }
            }).finally(() => { this.confirmLoading = false })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    handleInfo (record) {
      this.$router.push({
        name: 'projectInfo',
        path: '/project/projectInfo',
        query: {
          record: JSON.stringify(record)
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    tableCustomRow (record, index) {
      return {
        style: {
          'background-color': record.projectId === this.physicalSurveyCurrRowId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.physicalSurveyCurrRowId = record.projectId
            this.conRecord = record
            record.fileIds ? this.getFiles(record) : (this.files = [])
          }
        }
      }
    },
    resetProjectTypes () {
      getAllProjectType().then(res => {
        if (res.code === 0) {
          this.projectTypes = res.data
        }
      })
    }
  }
}
</script>
